# !/bin/usr/python
# _*_ coding=utf-8 _*_
# Filename : urllib2_postfile.py

import urllib2
import msvcrt
import os
from poster.encode import multipart_encode
from poster.streaminghttp import register_openers

# 二进制文件处理
msvcrt.setmode( 0, os.O_BINARY )

# poster http流处理注册
register_openers()

# 文件打开
filename = 'py.ico'
fp = open (filename, 'rb')

# multipart编码
datagen, headers = multipart_encode({'file1': fp})
# urllib2 request作成
request = urllib2.Request('http://192.168.1.55/urllib2_postfile_res.py', datagen, headers)
# head信息添加
request.add_header( 'Connection', 'Close' )

# 请求
try:
	res = urllib2.urlopen(request)
except urllib2.HTTPError, ee:
	# 请求失败
	print ('Request HTTPError: ', ee.code)
except urllib2.URLError, ee:
	# 请求失败
	print ('Request URLError: ', ee.reason)
else:
	# 结果输出
	print (res.read())
	res.close()
finally:
	# 文件关闭
	fp.close()


